package com.pzl.service.impl;

import com.pzl.mapper.RoleDao;
import com.pzl.mapper.UserDao;
import com.pzl.entity.Role;
import com.pzl.entity.User;
import com.pzl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserService class
 *
 * @Author panzhenglei
 * @Date 2019/6/8 9:37 AM
 */

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public Long save(User user,Long[] roleIds) {

        int i = userDao.save(user);
        userDao.saveUserRole(user,roleIds);
        if (i>0){
            return 1L;
        }
        return 0L;

    }

    @Override
    public List<User> findAll() throws Exception {
        List<User> users = userDao.findAll();
        for (User user : users) {
            List<Role> roles = roleDao.selectRid(user);
            user.setRoles(roles);
        }
        return users;
    }

    @Override
    public User findOne(Long id) throws Exception {
        User one = userDao.findOne(id);
        List<Role> roles = roleDao.selectRid(one);
        one.setRoles(roles);

        return one;
    }

    @Override
    public Long update(User user, Long[] roleIds) {
        int i = userDao.update(user);
        userDao.saveUserRole(user,roleIds);
        if (i>0){
            return 1L;
        }
        return 0L;

    }
}
